export default {
  data() {
    // 验证邮箱格式
    const validateEmail = (rule, value, callback) => {
      if (!/^([0-9A-Za-z\-_\]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g.test(value)) {
        callback(new Error('请注意邮箱书写格式'))
      }
      callback()
    }
    // 验证手机格式
    const validateMobile = (rule, value, callback) => {
      if (!/^1[3|4|5|8][0-9]\d{4,8}$/g.test(value)) {
        callback(new Error('请注意手机号书写格式'))
      }
      callback()
    }

    return {
      userSearch: '',
      addUserForm: [],
      query: '',
      pagenum: 1,
      pagesize: 2,
      total: 0,
      userDialogVisible: false,
      userRuleForm: {},
      userRules: {
        username: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
        password: [
          { required: true, message: '请填写用户密码', trigger: 'blur' },
          { min: 6, max: 18, message: '密码长度在6~18个字符', trigger: 'blur' }
        ],
        // /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g
        email: [
          { required: true, message: '请填写邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请填写邮箱', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
      editUserDialogVisible: false,
      editUserRuleForm: {},
      editUserRules: {
        email: [
          { required: true, message: '请填写邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请填写邮箱', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
      userInfo: {},
      roleDialogVisible: false,
      // 角色分配选择器
      roleOptions: [],
      // 被选中的角色
      selectedRole: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: { query: this.query, pagenum: this.pagenum, pagesize: this.pagesize }
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败!')
      this.addUserForm = res.data.users
      this.total = res.data.total
    },
    // 修改页码尺寸
    handleSizeChange(val) {
      this.pagesize = val
      this.getUserList()
    },
    // 修改页码
    handleCurrentChange(val) {
      this.pagenum = val
      this.getUserList()
    },
    // 搜索关键字
    search() {
      this.getUserList()
    },
    // 重置添加用户表单
    resetForm() {
      this.$refs.userFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.userFormRef.validate(async valid => {
        if (!valid) return
        // 存入
        const { data: res } = await this.$http.post('users', this.userRuleForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.userDialogVisible = false
        this.getUserList()
      })
    },
    // 修改状态
    async changeState(id, state) {
      const { data: res } = await this.$http.put(`users/${id}/state/${state}`)
      if (res.meta.status !== 200) return this.$message.error('修改状态失败')
    },
    // 获取个人信息表单
    async editFrom(id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取个人用户信息失败')
      this.editUserRuleForm = res.data
      this.editUserDialogVisible = true
    },
    // 重置个人信息表单
    editResetForm() {
      this.editUserRuleForm = {}
      this.$refs.editUserFormRef.resetFields()
      this.editUserDialogVisible = false
    },
    // 保存编辑个人信息
    saveUser(id) {
      this.$refs.editUserFormRef.validate(async valid => {
        if (!valid) return
        // 存入
        const { data: res } = await this.$http.put(`users/${id}`, {
          email: this.editUserRuleForm.email,
          mobile: this.editUserRuleForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editUserDialogVisible = false
        this.getUserList()
      })
    },
    // 移除个人用户信息
    removeForm(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const { data: res } = await this.$http.delete(`users/${id}`)
          console.log(res)
          if (res.meta.status !== 200) return this.$message.error('删除用户信息失败')
          this.$message.success('删除用户成功')
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 设置分配角色
    async setRoleForm(userInfo) {
      this.roleDialogVisible = true
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败！')
      this.roleOptions = res.data
    },
    // 重置分配角色
    roleResetForm() {
      this.selectedRole = ''
      this.roleDialogVisible = false
    },
    // 保存编辑角色
    async saveRole(id) {
      if (this.selectedRole === '') return this.$message.error('请选择新角色')
      // 存入
      const { data: res } = await this.$http.put(`users/${id}/role`, {
        rid: this.selectedRole
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.roleDialogVisible = false
      this.getUserList()
    }
  }
}
